package com.wy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.common.CustomException;
import com.wy.dto.SetmealDto;
import com.wy.entity.Setmeal;
import com.wy.entity.SetmealDish;
import com.wy.mapper.SetmealMapper;
import com.wy.service.SetmealDishService;
import com.wy.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1.保存套餐的基本信息
        this.save(setmealDto);
        //2.保存套餐和菜品的关联信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes =setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐操作
     * 删除的时候,套餐关联下的关系也要删除,两张表
     * @param ids
     */
    @Override
    public void removeWithDish(List<Long> ids) {
        //1.状态为停售状态才可以删除,创建查询条件
        LambdaQueryWrapper<Setmeal> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        //2.统计是否能够删除,count>0就可以删除,否则抛异常
        int count = this.count(queryWrapper);
        if (count<0){
            throw new CustomException("不符合条件");
        }
        //3.删除符合条件的setmeal套餐信息
        this.removeByIds(ids);
        //4.删除和套餐表相关联的信息,通过Setmeal中的ids值查询到setmealDish表中的id
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        //5.通过获取的id值,直接删除对应的信息
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
